//
//  FTWAPI.m
//  FTWDemo
//
//  Created by ZYYX on 9/10/14.
//  Copyright (c) 2014 acs. All rights reserved.
//

#import "FTWAPI.h"
#import "PersistencyManager.h"
#import "HTTPClient.h"

@interface FTWAPI()
{
    PersistencyManager *persistencyManager;
    HTTPClient *httpClient;
}

//@property (weak) UIImageView *_imageView;
@end

@implementation FTWAPI
-(id)init
{
    self = [super init];
    if (self) {
        persistencyManager = [[PersistencyManager alloc] init];
        httpClient = [[HTTPClient alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadImage:) name:@"BLDownloadImageNotification" object:nil];
//        _imageView = [[UIImageView alloc] init];
    }
    return self;
}

+ (FTWAPI*)sharedInstance
{
    
    static FTWAPI *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[FTWAPI alloc] init];
    });
    return _sharedInstance;
}


-(NSArray *)coverImages
{
    return [persistencyManager coverImages];
}


-(void)setupCoverImage:(UIImageView*)imageView withURL:(NSString*)imageURL
{
    [imageView addObserver:self forKeyPath:@"image" options:0 context:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BLDownloadImageNotification"
                                                        object:self
                                                      userInfo:@{@"imageView":imageView, @"coverUrl":imageURL}];
}

- (void)downloadImage:(NSNotification*)notification
{
    // 1
    UIImageView* imageView = notification.userInfo[@"imageView"];
    NSString *coverUrl = notification.userInfo[@"coverUrl"];
    
    // 2
    imageView.image = [persistencyManager getImage:[coverUrl lastPathComponent]];
    
    if (imageView.image == nil)
    {
    	// 3
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *image = [httpClient downloadImage:coverUrl];
            
            // 4
            dispatch_sync(dispatch_get_main_queue(), ^{
                imageView.image = image;
                [persistencyManager saveImage:image filename:[coverUrl lastPathComponent]];
            });
        });
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"image"])
    {
//        [indicator stopAnimating];
        [object removeObserver:self forKeyPath:@"image"];
    }
}

- (void)dealloc
{
//
}



@end
